package com.prothink.threadproject.xiancheng;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ComputerFactory {

    // 创建一个阻塞队列，模拟生产和搬运电脑
    private static final BlockingQueue<String> computerQueue = new LinkedBlockingQueue<>();

    public static void main(String[] args) {
        // 创建生产电脑线程
        Thread producerThread = new Thread(new ComputerProducer());
        // 创建搬运电脑线程
        Thread consumerThread = new Thread(new ComputerConsumer());

        // 启动线程
        producerThread.start();
        consumerThread.start();
    }

    // 生产电脑的生产者线程
    static class ComputerProducer implements Runnable {
        private static final String COMPUTER = "电脑";

        @Override
        public void run() {
            int count = 1;
            while (true) {
                try {
                    // 生产电脑
                    String computer = COMPUTER + count;
                    System.out.println("生产出一台 " + computer);
                    // 将电脑放入阻塞队列
                    computerQueue.put(computer);
                    count++;
                    // 模拟生产过程的时间
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("生产线程被中断");
                }
            }
        }
    }

    // 搬运电脑的消费者线程
    static class ComputerConsumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 从阻塞队列中取出电脑
                    String computer = computerQueue.take();
                    System.out.println("搬运走一台 " + computer);
                    // 模拟搬运过程的时间
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("搬运线程被中断");
                }
            }
        }
    }
}
